import {BrowserWindow, ipcMain} from "electron";

const path = require('node:path')

// 存储所有子窗口的引用（如果需要多个）
const childWindows = new Map();

// 创建子窗口的函数
function createChildWindow(routePath, options = {}) {
    const windowKey = routePath; // 可以用路由作为唯一键
    // 如果窗口已存在且未被销毁，则聚焦并返回
    if (childWindows.has(windowKey)) {
        const existingWindow = childWindows.get(windowKey);
        if (!existingWindow.isDestroyed()) {
            existingWindow.focus();
            return existingWindow;
        }
    }

    const childWindow = new BrowserWindow({
        width: 1280,
        height: 720,
        // maximizable: true,
        // fullscreen: true,
        parent: global.mainWindow, // 设置为子窗口
        modal: true, // 非模态窗口
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js')
        },
        ...options
    });
    if (options.fakeClose) {
        // 拦截 close 事件，改为隐藏窗口
        childWindow.on('close', (e) => {
            e.preventDefault(); // 阻止默认关闭行为
            childWindow.webContents.send('on-child-window-message', {type: 'close'})
            childWindow.hide(); // 改为隐藏
        });
    }

    // 构建带有路由参数的 URL

    if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
        childWindow.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL + `/#${routePath}`);
    } else {
        childWindow.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html#${routePath}`));
    }

    // 存储窗口引用
    childWindows.set(windowKey, childWindow);
    // 窗口关闭时清理引用
    childWindow.on('closed', () => {
        childWindows.delete(windowKey);
    });

    if (!import.meta.env.PROD) {
        childWindow.webContents.openDevTools(); // 开发者控制台
    }

    return childWindow;
}


export function setChildWindow() {
    // IPC 处理：接收创建窗口的请求
    ipcMain.handle('create-child-window', (event, routePath, options = {}) => {
        createChildWindow(routePath, options);
    });

    // 显示窗口
    ipcMain.handle('show-child-window', (event, routePath) => {
        const window = childWindows.get(routePath);
        if (window && !window.isDestroyed()) {
            window.show();
            return true;
        }
        return false;
    });

    // 隐藏窗口
    ipcMain.handle('hide-child-window', (event, routePath) => {
        const window = childWindows.get(routePath);
        if (window && !window.isDestroyed()) {
            window.hide();
            return true;
        }
        return false;
    });

    // 关闭窗口
    ipcMain.handle('close-child-window', (event, routePath) => {
        const window = childWindows.get(routePath);
        if (window && !window.isDestroyed()) {
            window.close();
            return true;
        }
        return false;
    });

    // 检查窗口是否存在
    ipcMain.handle('is-child-window-exists', (event, routePath) => {
        const window = childWindows.get(routePath);
        return !!window && !window.isDestroyed();
    });

    ipcMain.handle('send-child-window-message', (event, routePath, msg) => {
        console.log('send-child-window-message', msg)
        const window = childWindows.get(routePath);
        window.webContents.send('on-child-window-message', msg)
    });
}